/**
 * Created by root on 14-7-22.
 */
(function(){
 var canvas = document.getElementById('canvas')
   , context = canvas.getContext('2d')
   , FONT_HEIGHT = 15
   , MARGIN = 32
   , HAND_TRUNCACTION = canvas.width/25
   , HOUR_HAND_TRUNACTION = canvas.width/10
   , NUMEAL_SPACING = 20
   , RADIUS = canvas.width/2 - MARGIN
   , HAND_RADIUS = RADIUS + NUMEAL_SPACING;

  //绘制圆形
  function drawCircle() {
    context.beginPath();
    context.arc(canvas.width/2, canvas.height/2, RADIUS, 0, Math.PI*2, false);
    context.stroke();
  }

  //绘制数字
  function drawNumerals() {
    var numerals = [1,2,3,4,5,6,7,8,9,10,11,12]
      , angle = 0
      , numeralWidth = 0;

    numerals.forEach(function(numberal) {
      angle = Math.PI/6 * (numberal-3);
      numeralWidth = context.measureText(numberal).width;
      context.fillText(numberal, canvas.width/2 + Math.cos(angle)*(HAND_RADIUS) - numeralWidth/2, canvas.height/2 + Math.sin(angle)*(HAND_RADIUS) + FONT_HEIGHT/3);
    });
  }

  //绘制中心点
  function drawCenter() {
    context.beginPath();
    context.arc(canvas.width/2, canvas.height/2, 5, 0, Math.PI*2, true);
    context.fill();
  }

  //绘制指针
  function drawHand(loc, isHour) {
    var angle = (Math.PI*2) * (loc/60) - Math.PI/ 2
      , handRadius = isHour ? RADIUS - HAND_TRUNCACTION - HOUR_HAND_TRUNACTION : RADIUS - HAND_TRUNCACTION;

    context.moveTo(canvas.width/2, canvas.height/2);
    context.lineTo(canvas.width/2 + Math.cos(angle)*handRadius, canvas.height/2 + Math.sin(angle)*handRadius);
    context.stroke();
  }

  //绘制指针
  function drawHands() {
    var date = new Date
      , hour = date.getHours();

    hour = hour > 12 ? hour - 12 : hour;

    drawHand(hour*5 + (date.getMinutes()/60*5), true);
    drawHand(date.getMinutes(), false);
    drawHand(date.getSeconds(), false);
  }

  //绘制时钟
  function drawClock() {
    context.clearRect(0, 0, canvas.width, canvas.height);

    drawCircle();
    drawCenter();
    drawHands();
    drawNumerals();

    var img = document.getElementsByTagName('img')[0];
    if (img) {
      img.src = canvas.toDataURL();
    } else {
      img = document.createElement('img');
      img.src = canvas.toDataURL();
      document.body.appendChild(img);
    }

  }

  context.font = FONT_HEIGHT + 'px Arial';
  setInterval(drawClock, 1000);

})();